﻿using DotNet.Utilities.WpfHelpers;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;

namespace WPFPractice.Windows
{
    /// <summary>
    /// ComboBox 绑定资源键示例；
    /// </summary>
    public partial class WinComboBox : Window
    {
        private ComboBoxViewModel _VM;

        public WinComboBox()
        {
            Title = nameof(WinComboBox);
            InitializeComponent();

            _VM = new ComboBoxViewModel();
            DataContext = _VM;
        }
    }

    [AddINotifyPropertyChangedInterface]
    public class ComboBoxViewModel : BindableBase
    {
        #region 成员

        /// <summary>
        /// 状态信息
        /// </summary>
        public string StatusInfo { get; set; }

        /// <summary>
        /// 时间列表
        /// </summary>
        public ObservableCollection<KeyValuePair<string, int>> TimeList { get; set; } = new ObservableCollection<KeyValuePair<string, int>>()
        {
            new KeyValuePair<string, int>("LockTime-OneMinute", 1),
            new KeyValuePair<string, int>("LockTime-FiveMinute", 5),
            new KeyValuePair<string, int>("LockTime-TenMinute", 10),
            new KeyValuePair<string, int>("LockTime-FifteenMinute", 15),
            new KeyValuePair<string, int>("LockTime-ThirtyMinute", 30),
            new KeyValuePair<string, int>("LockTime-OneHour", 60),
            new KeyValuePair<string, int>("LockTime-TwoHour", 120),
            new KeyValuePair<string, int>("LockTime-ThreeHour", 180),
            new KeyValuePair<string, int>("LockTime-Never", 0),
        };

        /// <summary>
        /// 选择的时间（显示，分钟）
        /// </summary>
        public KeyValuePair<string, int> SelectedTime { get; set; }

        /// <summary>
        /// 语言名称列表
        /// </summary>
        private readonly List<string> _LangKeys = new List<string>() { "en-us", "zh-cn" };

        /// <summary>
        /// 语言资源路径模板字符串
        /// </summary>
        private string _LangResourceUriTemplate = "/WPFPractice;component/Resources/Language/{0}.xaml";

        #endregion

        public ComboBoxViewModel()
        {
            SetCommandMethod();

            ApplyLanguage(_LangResourceUriTemplate);
        }

        #region 辅助方法

        public void ShowInfo(string info)
        {
            StatusInfo = $"{info}";
        }

        /// <summary>
        /// 应用语言
        /// </summary>
        /// <param name="packUriTemplate">资源路径模板，形如："/WPFPractice;component/Resources/Language/{0}.xaml"</param>
        /// <param name="langName">语言名称，形如："zh-cn"</param>
        private void ApplyLanguage(string packUriTemplate, string langName = "zh-cn")
        {
            var rd = Application.Current.Resources;
            //RemoveLangThemes();

            var packUri = string.Format(packUriTemplate, langName);
            RemoveLangThemes(new List<string>() { langName });

            //将资源加载在最后，优先使用;
            rd.MergedDictionaries.Add((ResourceDictionary)Application.LoadComponent(new Uri(packUri, UriKind.Relative)));
        }

        /// <summary>
        /// 移除语言资源
        /// </summary>
        /// <param name="removeKeyList">需要移除的资源中包含的key的列表，默认为空，为空移除所有的</param>
        private void RemoveLangThemes(List<string> removeKeyList = null)
        {
            if (removeKeyList == null)
            {
                removeKeyList = _LangKeys;
            }

            var rd = Application.Current.Resources;
            List<ResourceDictionary> removeList = new List<ResourceDictionary>();

            foreach (var dictionary in rd.MergedDictionaries)
            {
                //判断是否是对应的语言资源文件;
                bool isExists = removeKeyList.Exists(x => dictionary.Contains("LangName") && dictionary["LangName"]+"" == x);
                if (isExists)
                {
                    removeList.Add(dictionary);
                }
            }

            foreach (var removeResource in removeList)
            {
                rd.MergedDictionaries.Remove(removeResource);
            }
        }

        #endregion

        #region 命令

        public ICommand SwitchCnCmd { get; set; }

        public ICommand SwitchEnCmd { get; set; }

        #endregion

        /// <summary>
        /// 命令方法赋值（在构造方法中调用）
        /// </summary>
        private void SetCommandMethod()
        {
            SwitchCnCmd ??= new RelayCommand(o => true, async o =>
            {
                ApplyLanguage(_LangResourceUriTemplate, "zh-cn");
            });

            SwitchEnCmd ??= new RelayCommand(o => true, async o =>
            {
                ApplyLanguage(_LangResourceUriTemplate, "en-us");
            });
        }
    }
}
